/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.core.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import io.jboot.utils.StrUtil;
import io.jboot.web.controller.JbootController;
import io.jplus.JplusConsts;
import io.jplus.core.exception.JplusException;
import io.jplus.core.plugin.jwt.JwtToken;

/**
 * @author Retire 吴益峰 （372310383@qq.com）
 * @version V1.0
 * @Package io.jplus.core.interceptor
 */
public class JwtTokenInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        if (inv.getController() instanceof JbootController) {
            JbootController c = (JbootController) inv.getController();
            String userId = c.getJwtPara("userId");
            String version = c.getJwtPara("version");

            if (StrUtil.isBlank(userId) || StrUtil.isBlank(version)) {
                return;
            }

            // 此处1L 为测试，实际会从服务获取
            if (!"1".equals(userId)) {
                throw new JplusException("not auth");
            }

            JwtToken jwtToken = c.getSessionAttr(JplusConsts.JWT_TOKEN);
            if (jwtToken == null) {
                throw new JplusException("not auth");
            }

            if (!jwtToken.getVersion().equals(version)) {
                throw new JplusException("not auth");
            }
        }

        inv.invoke();
    }
}
